package com.example.webview_interactive;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by josan_tang on 9/5/17.
 */

public class MyWebView extends WebView{
    private static final String TAG = "MyWebView";
    /** 网页需要调用触发协议时，发送该消息 **/
    public static final int TRIGGER_INTERACTIVE = 1000;
    private List<String> registerKeyArr;
    private Context mContext;

    private MyHandler mHandler;

    public MyWebView(Context context) {
        this(context, null);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化
        init();
    }

    /**
     * 初始化操作
     */
    private void init() {
        mContext = this.getContext();
        //创建一个订阅名的数组，用户保存H5注册时的注册名
        registerKeyArr = new ArrayList<>();
        //允许使用Js
        getSettings().setJavaScriptEnabled(true);
        //创建一个Handler
        mHandler = new MyHandler(this);
        //将创建的handler加入到集合中，以便实现广播
        MessageUtils.getInstance().registerHandler(this.hashCode()+"", mHandler);
        //设置WebViewClient
        setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e(TAG, "shouldOverrideUrlLoading: url:" + url);
                //如果网页调用了注册协议，比如：josan://register/login
                if (url.contains("josan://register/")) {    //订阅协议，即H5 A中触发
                    //这里取出login，作为群发消息的key
                    String registerName = url.replace("josan://register/", "");
                    if (!registerKeyArr.contains(registerName)) {
                        //存入到当前WebView的订阅名集合中
                        registerKeyArr.add(registerName);
                    }
                } else if (url.contains("josan://trigger/")) {  //发布协议，即H5 B中触发
                    //如果网页调用了触发协议，比如：josan://trigger/login/logined
                    String triggerNameAndCallback = url.replace("josan://trigger/", "");
                    MessageUtils.getInstance().sendOverallMessage(TRIGGER_INTERACTIVE, triggerNameAndCallback);
                } else if (url.contains("josan://openSecondActivity/")){
                    //用协议启动第二个Activity
                    Intent intent = new Intent(mContext, SecondActivity.class);
                    mContext.startActivity(intent);
                } else {
                    view.loadUrl(url);
                }
                return true;
            }
        });

    }


    private static class MyHandler extends Handler {
        private WeakReference<WebView> weakWebView;

        public MyHandler(WebView webView) {
            weakWebView = new WeakReference<WebView>(webView);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                super.handleMessage(msg);
                switch (msg.what) {
                    case TRIGGER_INTERACTIVE:   //网页调用触发协议时,格式为:  registerName/callbackName/params1/param2/param...
                        String triggerNameAndCallback = (String) msg.obj;
                        String[] nameAndCallbackArr = triggerNameAndCallback.split("/");
                        if (nameAndCallbackArr.length >= 2) {
                            String triggerName = nameAndCallbackArr[0];
                            String triggerCall = nameAndCallbackArr[1];
                            MyWebView webview = (MyWebView) weakWebView.get();
                            if (webview != null && webview.registerKeyArr.contains(triggerName)) {
                                String callbackUrl = "javascript:" + triggerCall + "(";
                                for (int i = 2; i < nameAndCallbackArr.length; i++) {
                                    callbackUrl += "'" + nameAndCallbackArr[i] + "',";
                                }
                                if (nameAndCallbackArr.length > 2) {
                                    callbackUrl = callbackUrl.substring(0, callbackUrl.length() - 1);
                                }
                                callbackUrl += ")";
                                Log.e(TAG, "callbackUrl:" + callbackUrl);
                                webview.loadUrl(callbackUrl);
                            }
                        }
                        break;
                    default:
                        break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        //反注册handler
        MessageUtils.getInstance().unregisterHandler(this.hashCode()+"");
    }
}
